package com.ruicar.afs.cloud.channel.online.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.channel.channelworkflow.condition.ChannelOnlineWorkFlowCondition;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskApproveRecordService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.common.condition.BaseInfoTypeDTO;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.mq.sender.ChannelOnlineInfoToCaseSender;
import com.ruicar.afs.cloud.channel.common.mq.sender.config.ArchiveConfig;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToArchiveImpl;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.common.until.RoleTypeDic;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelAppertainRegion;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelUser;
import com.ruicar.afs.cloud.channel.mange.entity.ChannelUserAppertain;
import com.ruicar.afs.cloud.channel.mange.enums.RegionLevel;
import com.ruicar.afs.cloud.channel.mange.service.ChannelAppertainRegionService;
import com.ruicar.afs.cloud.channel.mange.service.ChannelUserAppertainService;
import com.ruicar.afs.cloud.channel.mange.service.ChannelUserService;
import com.ruicar.afs.cloud.channel.online.condition.*;
import com.ruicar.afs.cloud.channel.online.entity.*;
import com.ruicar.afs.cloud.channel.online.service.*;
import com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants;
import com.ruicar.afs.cloud.channel.online.vo.ChannelOnlineInfoVo;
import com.ruicar.afs.cloud.channel.online.vo.ChannelOnlineInterFaceVo;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.*;

/**
 * @ClassName:ChannelOnlineController
 * @Description: 渠道上线申请保存信息-controller
 * @Author:mingzhi.li
 * @Date:2020/5/18 19:06
 * @Version: V1.0
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/channelOnline")
@Api(value = "channelOnline", description = "渠道上线申请")
public class ChannelOnlineController {
    /**
     * 基本信息
     */
    @Autowired
    private ChannelOnlineService channelOnlineService;

    /**
     * 收款账号
     */
    @Autowired
    private ChannelAccountInfoService channelAccountInfoService;

    /**
     * 风控数据
     */
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;

    /**
     * 保证金
     */
    @Autowired
    private ChannelQuotaInfoService channelQuotaInfoService;

    /**
     * 授权区域
     */
    @Autowired
    private ChannelAuthorizeRegionService channelAuthorizeRegionService;

    /**
     * 建档日期
     */
    @Autowired
    private ChannelArchivesInfoService channelArchivesInfoService;

    /**
     *
     */
    private TsysAddressParamService service;

    /**
     * 授权车型
     */
    @Autowired
    private ChannelAuthorizeVehicleTempService channelAuthorizeVehicleTempService;

    /**
     * 主营品牌
     */
    @Autowired
    private ChannelMainBrandService channelMainBrandService;

    private final ChannelUserService userService;
    private final SenderChannelToArchiveImpl senderChannelToArchiveImpl;
    /**
     * 工作流
     */
    private final WorkflowService workflowService;
    private final WorkTaskDetailService workTaskDetailService;
    private final UidGenerator uidGenerator;
    private final WorkTaskApproveRecordService workTaskApproveRecordService;
    /**
     * 授权区域
     */
    private final ChannelAppertainRegionService appertainRegionService;
    private final ChannelUserAppertainService userAppertainService;
    private final ChannelConfig channelConfig;
    private final ChannelUseCaseService channelUseCaseService;
    private final ChannelOnlineInfoToCaseSender channelOnlineInfoToCaseSender;

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "保存渠道上线申请信息")
    @SysLog("保存渠道上线申请信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveOrUpdate(@RequestBody ChannelOnlineCondition channelOnlineCondition) {

        List list = new ArrayList<>();
        //渠道基本信息
        ChannelBaseInfoTemp temp = channelOnlineCondition.getChannelBaseInfoTemp();
        Long newId = temp.getId();
        if (!StrUtil.isBlank(temp.getSocUniCrtCode())) {
            List<ChannelBaseInfoTemp> socUniCrtCodeList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, temp.getSocUniCrtCode()));
            if (newId == null) {
                if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                    return IResponse.fail("当前统一社会信用代码已存在!");
                }
            } else {
                Long oldId = null;
                if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                    for (ChannelBaseInfoTemp baseInfoTemp : socUniCrtCodeList) {
                        oldId = baseInfoTemp.getId();
                        if (!oldId.equals(newId)) {
                            return IResponse.fail("系统已存在当前统一社会信用代码,操作失败!");
                        }
                    }
                }
            }
        }
        ChannelBaseInfoTemp baseInfoTemp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, newId));


        //管理员所在省市
        String[] channelAdminAddressValue = channelOnlineCondition.getChannelAdminAddressValue();
        //注册地所在省市
        String[] channelAddressValue = channelOnlineCondition.getChannelAddressValue();
        //办公所在省市
        String[] officeAddressValue = channelOnlineCondition.getOfficeAddressValue();
        //新车授权区域
        String[] mainArea = channelOnlineCondition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = channelOnlineCondition.getMainAreaOld();
        //主营品牌
        String[] mainBrand = channelOnlineCondition.getMainBrand();
        //授权车型
        String[] mainCar = channelOnlineCondition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = channelOnlineCondition.getMainCarOld();
        //判断管理员地址是否为空
        if (channelAdminAddressValue != null && channelAdminAddressValue.length > 0) {
            temp.setChannelAdminProvince(channelAdminAddressValue[0]);
            temp.setChannelAdminCity(channelAdminAddressValue[1]);
        }
        //判断注册省份是否为空
        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }
        //判断办公省份是否为空
        if (officeAddressValue != null && officeAddressValue.length > 0) {
            temp.setOfficeProvince(officeAddressValue[0]);
            temp.setOfficeCity(officeAddressValue[1]);
        }
        if (StrUtil.isBlank(temp.getChannelCode())) {
            //渠道代码为空则按照规则从新拼接
            temp.setChannelCode(channelOnlineService.channelCodeSequence(VALUE_CHANNEL_CODE, VALUE_CHANNEL_CODE));
        }
        //默认状态：草稿,只处理一次，没有对应权限更新为空
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {
            if (baseInfoTemp == null) {
                temp.setChannelStatus(VALUE_CHANNEL_STATUS_TWO);
            } else if (!VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatus())) {
                temp.setChannelStatus(VALUE_CHANNEL_STATUS_TWO);
            }
        } else {
            if (StrUtil.isBlank(temp.getChannelStatus())) {
                temp.setChannelStatus("");
            }
        }
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            if (baseInfoTemp == null) {
                temp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_TWO);
            } else if (!VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatusOldCar())) {
                temp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_TWO);
            }
        } else {
            if (StrUtil.isBlank(temp.getChannelStatusOldCar())) {
                temp.setChannelStatusOldCar("");
            }
        }
        channelOnlineService.saveOrUpdate(temp);
        list.add(temp);
        /** 保存渠道主营品牌信息前先清除旧的数据*/
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda().eq(ChannelMainBrand::getChannelId, temp.getId().toString()));

        //保存渠道主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrand.setChannelBelong(temp.getChannelBelong());
                channelMainBrandList.add(channelMainBrand);
            }
            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {

            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTemp();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);

            //保存新车保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }

            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }

            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
        }

        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTempOld();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);

            //保存二手车保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempOldList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }
            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }

            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
        }

        return IResponse.success(list);
    }

    @PostMapping("/getChannelBasicInfo")
    @ApiOperation(value = "获取渠道基本信息")
    @SysLog("获取渠道基本信息")
    public IResponse getChannelBasicInfo(ChannelOnlineCondition channelOnlineCondition) {
        List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getChannelCode, channelOnlineCondition.getId()));
        Map<String, String> map = new HashMap<>();
        list.stream().forEach(ChannelBaseInfoTemp -> {
                    map.put(String.valueOf(ChannelBaseInfoTemp.getId()), ChannelBaseInfoTemp.getChannelCode());
                }
        );
        return new IResponse<Map<String, String>>().setData(map);
    }

    @RequestMapping(value = "/getInfoById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取基本信息")
    public IResponse<List<ChannelBaseInfoTemp>> getInfoById(@PathVariable String id) {
        List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, id));
        return new IResponse<List<ChannelBaseInfoTemp>>().setData(list);
    }

    @RequestMapping(value = "/getRiskById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取风控信息")
    public IResponse<List<ChannelRiskInfoTemp>> getRiskById(@PathVariable String id) {
        List<ChannelRiskInfoTemp> list = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, id));
        return new IResponse<List<ChannelRiskInfoTemp>>().setData(list);
    }

    @RequestMapping(value = "/getQuotaInfoById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取保证金信息")
    public IResponse<List<ChannelQuotaInfoTemp>> getQuotaInfoById(@PathVariable String id) {
        List<ChannelQuotaInfoTemp> list = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda().eq(ChannelQuotaInfoTemp::getChannelId, id));
        return new IResponse<List<ChannelQuotaInfoTemp>>().setData(list);
    }

    @RequestMapping(value = "/getMainAreaById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取授权区域信息")
    public IResponse<List<ChannelAuthorizeRegionTemp>> getMainAreaById(@PathVariable String id) {
        List<ChannelAuthorizeRegionTemp> list = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda().eq(ChannelAuthorizeRegionTemp::getChannelId, id));
        return new IResponse<List<ChannelAuthorizeRegionTemp>>().setData(list);
    }

    @RequestMapping(value = "/getNewMainAreaById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取新车授权区域信息")
    public IResponse<List<ChannelAuthorizeRegionTemp>> getNewMainAreaById(@PathVariable String id) {
        List<ChannelAuthorizeRegionTemp> list = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                .eq(ChannelAuthorizeRegionTemp::getChannelId, id)
                .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
        return new IResponse<List<ChannelAuthorizeRegionTemp>>().setData(list);
    }

    @RequestMapping(value = "/getOldMainAreaById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取二手车授权区域信息")
    public IResponse<List<ChannelAuthorizeRegionTemp>> getOldMainAreaById(@PathVariable String id) {
        List<ChannelAuthorizeRegionTemp> list = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                .eq(ChannelAuthorizeRegionTemp::getChannelId, id)
                .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
        return new IResponse<List<ChannelAuthorizeRegionTemp>>().setData(list);
    }

    @RequestMapping(value = "/getMaiBrandById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取主营品牌信息")
    public IResponse<List<ChannelMainBrand>> getMaiBrandById(@PathVariable String id) {
        List<ChannelMainBrand> list = channelMainBrandService.list(Wrappers.<ChannelMainBrand>query().lambda().eq(ChannelMainBrand::getChannelId, id));
        return new IResponse<List<ChannelMainBrand>>().setData(list);
    }

    @RequestMapping(value = "/getVehicleById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取授权车型信息")
    public IResponse<List<ChannelAuthorizeVehicleTemp>> getVehicleById(@PathVariable String id) {
        List<ChannelAuthorizeVehicleTemp> list = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda().eq(ChannelAuthorizeVehicleTemp::getChannelId, id));
        return new IResponse<List<ChannelAuthorizeVehicleTemp>>().setData(list);
    }

    @RequestMapping(value = "/getNewVehicleById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取新车授权车型信息")
    public IResponse<List<ChannelAuthorizeVehicleTemp>> getNewVehicleById(@PathVariable String id) {
        List<ChannelAuthorizeVehicleTemp> list = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                .eq(ChannelAuthorizeVehicleTemp::getChannelId, id)
                .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
        return new IResponse<List<ChannelAuthorizeVehicleTemp>>().setData(list);
    }

    @RequestMapping(value = "/getOldVehicleById/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "根据渠道id获取二手车授权车型信息")
    public IResponse<List<ChannelAuthorizeVehicleTemp>> getOldVehicleById(@PathVariable String id) {
        List<ChannelAuthorizeVehicleTemp> list = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                .eq(ChannelAuthorizeVehicleTemp::getChannelId, id)
                .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
        return new IResponse<List<ChannelAuthorizeVehicleTemp>>().setData(list);
    }

    @PostMapping(value = "/getByCondition")
    @ApiOperation(value = "多条件分页渠道信息列表")
    public IResponse<ChannelBaseInfoTemp> getByCondition(@RequestBody ChannelOnlineCondition condition) {
        IResponse<ChannelOnlineInfoVo> channelList = channelOnlineService.getByCondition(condition);
        return IResponse.success(channelList);
    }

    @PostMapping(value = "/getAreaListCondition")
    @ApiOperation(value = "多条件分页获取渠道展业")
    public IResponse<IPage<ChannelBaseInfoTemp>> getAreaListCondition(@RequestBody ChannelOnlineCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getAreaListCondition(page, condition);
        return IResponse.success(channelList);
    }

    @PostMapping("/getArchivesLogInfo")
    @ApiOperation(value = "分页查询档案日志信息")
    public IResponse<IPage<ChannelArchivesInfo>> getArchivesLogInfo(@RequestBody ArchivesLogInfoCondition condition) {
        IPage<ChannelArchivesInfo> list = channelArchivesInfoService.page(new Page(condition.getPageNumber(), condition.getPageSize())
                , Wrappers.<ChannelArchivesInfo>query().lambda()
                        .eq(condition.getChannelId() != null, ChannelArchivesInfo::getChannelId, condition.getChannelId()));
        return IResponse.success(list);
    }


    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    @Transactional
    @SysLog("批量通过ids删除")
    public IResponse<Boolean> delAllByIds(@PathVariable String[] ids) {
        channelOnlineService.removeByIds(Arrays.asList(ids));
        return new IResponse<Boolean>().setMsg("批量通过id删除数据成功");
    }

    /**
     * 收款账号信息录入
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional
    @RequestMapping(value = "/saveAccountInfo", method = RequestMethod.POST)
    @CacheEvict(value = "channel_receivables_account_temp", allEntries = true)
    @ApiOperation(value = "保存数据")
    public IResponse saveAccountInfo(@Valid @RequestBody ChannelAccountInfoCondition condition) throws ParseException {
        ChannelReceivablesAccountTemp temp = condition.getChannelReceivablesAccountTemp();
        List<ChannelReceivablesAccountTemp> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getChannelId())
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, temp.getAccountAttribute())
                .eq(ChannelReceivablesAccountTemp::getCollectionType, temp.getCollectionType())
                .or().eq(ChannelReceivablesAccountTemp::getStatus, ACCOUNT_STATUS_TWO)
                .eq(ChannelReceivablesAccountTemp::getStatus, ACCOUNT_STATUS_ZERO));
        if (accountList != null && accountList.size() > 0) {
            return IResponse.fail("此类收款账号已建立！");
        }
        temp.setStatus(ACCOUNT_STATUS_TWO);
        channelAccountInfoService.save(temp);
        return IResponse.success(Boolean.TRUE).setMsg("录入成功");
    }

    /**
     * 收款账号修改
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @Transactional
    @RequestMapping(value = "/updateAccountInfo", method = RequestMethod.POST)
    @CacheEvict(value = "channel_receivables_account_temp", allEntries = true)
    @ApiOperation(value = "修改数据")
    public IResponse updateAccountInfo(@Valid @RequestBody ChannelAccountInfoCondition condition) throws ParseException {
        List<ChannelReceivablesAccountTemp> list = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                .eq(ChannelReceivablesAccountTemp::getChannelId, condition.getChannelId())
                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, condition.getAccountAttribute())
                .eq(ChannelReceivablesAccountTemp::getCollectionType, condition.getCollectionType())
                .ne(ChannelReceivablesAccountTemp::getId, condition.getId().toString())
                .eq(ChannelReceivablesAccountTemp::getStatus, ACCOUNT_STATUS_TWO)
        );

        if (list.size() > 0) {
            return IResponse.fail("已存在草稿状态的同类型账号");
        }

        condition.setStatus(ACCOUNT_STATUS_TWO);
        channelAccountInfoService.updateById(condition);
        return IResponse.success(Boolean.TRUE).setMsg("录入成功");
    }

    @RequestMapping(value = "/deleteAccount/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除收款账号信息")
    @Transactional
    @SysLog("通过ids删除")
    public IResponse<Boolean> deleteAccount(@PathVariable String[] ids) {
        channelAccountInfoService.removeByIds(Arrays.asList(ids));
        return new IResponse<Boolean>().setMsg("通过id删除数据成功");
    }

    /**
     * 根据多条件，分页获取收款账号信息
     *
     * @param condition
     * @return
     */
    @RequestMapping(value = "/getAccountInfo", method = RequestMethod.POST)
    @ApiOperation(value = "多条件分页获取收款账号信息")
    public IResponse<IPage<ChannelReceivablesAccountTemp>> getAccountInfo(@ModelAttribute ChannelAccountInfoCondition condition) {
        //渠道id为空null
        if (condition.getChannelId() == null) {
            return IResponse.fail("渠道id不能为空");
        }
        IPage<ChannelReceivablesAccountTemp> list = channelAccountInfoService.page(new Page(condition.getPageNumber(), condition.getPageSize())
                , Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(condition.getChannelId() != null, ChannelReceivablesAccountTemp::getChannelId, condition.getChannelId()));
        return IResponse.success(list);
    }

    /**
     * 渠道发票信息保存
     *
     * @param channelOnlineCondition
     * @return
     * @throws ParseException
     */
    @Transactional
    @RequestMapping(value = "/saveInvoiceInfo", method = RequestMethod.POST)
    @ApiOperation(value = "修改渠道发票信息")
    public IResponse saveInvoiceInfo(@RequestBody ChannelOnlineCondition channelOnlineCondition) throws ParseException {
        ChannelBaseInfoTemp temp = channelOnlineCondition.getChannelBaseInfoTemp();
        List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, temp.getId()));
        ChannelBaseInfoTemp infoTemp = null;
        if (list != null && list.size() > 0) {
            infoTemp = list.get(0);
            infoTemp.setTaxpayerType(temp.getTaxpayerType());
            infoTemp.setTaxpayerIdNumber(temp.getTaxpayerIdNumber());
            infoTemp.setInvoiceTelNumber(temp.getInvoiceTelNumber());
            infoTemp.setInvoiceAddress(temp.getInvoiceAddress());
            infoTemp.setOpeningBank(temp.getOpeningBank());
            infoTemp.setBankAccount(temp.getBankAccount());
            infoTemp.setTaxRate(temp.getTaxRate());
            channelOnlineService.updateById(infoTemp);
        }
        return IResponse.success(infoTemp);
    }

    @PostMapping("/socUniCrtCodeCheck")
    @ApiOperation(value = "校验统一社会信用代码")
    public Object checkBlack(@RequestBody ChannelOnlineCondition condition) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Long newId = condition.getId();
            if (!StrUtil.isBlank(condition.getSocUniCrtCode())) {
                List<ChannelBaseInfoTemp> socUniCrtCodeList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, condition.getSocUniCrtCode()));
                if (newId == null) {
                    if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                        resultMap.put("yes", TYPE_YES);
                    }
                } else {
                    String oldId = null;
                    if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                        for (ChannelBaseInfoTemp baseInfoTemp : socUniCrtCodeList) {
                            oldId = baseInfoTemp.getId().toString();
                            if (!oldId.equals(newId.toString())) {
                                resultMap.put("yes", TYPE_YES);
                            }
                        }
                    }
                }
                resultMap.put("code", "0000");
                resultMap.put("msg", "success");
            }
        } catch (Exception e) {
            resultMap.put("code", "9999");
            resultMap.put("msg", "查询失败，请联系管理员！");
        }
        return resultMap;
    }

    @RequestMapping(value = "/channelSubmit", method = RequestMethod.POST)
    @ApiOperation(value = "渠道上线审批通过逻辑处理")
    @SysLog("渠道上线审批通过逻辑处理")
    @Transactional(rollbackFor = Exception.class)
    public IResponse channelSubmit(@RequestBody ChannelOnlineCondition channelOnlineCondition) {
        ChannelBaseInfoTemp temp = channelOnlineCondition.getChannelBaseInfoTemp();
        //Step 1：修改渠道状态为 00：启用
        List<ChannelBaseInfoTemp> list = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, temp.getId()));
        String isNewCarRole = channelOnlineCondition.getIsNewCarRole();
        String isOldCarRole = channelOnlineCondition.getIsOldCarRole();
        if (list != null && list.size() > 0) {
            ChannelBaseInfoTemp infoTemp = list.get(0);

            //提交验证汇款对象是否为主体：如果是则上线阶段需要验证是否录入过收款账号
            //新车验证
            if (IS_HAVE_CAR_ROLE_YES.equals(isNewCarRole)) {
                if (!StrUtil.isBlank(infoTemp.getChannelStatus())) {
                    infoTemp.setChannelStatus(VALUE_CHANNEL_STATUS_ZERO);
                }
                if (PAYMENT_OBJECT_ZERO.equals(infoTemp.getPaymentObject())) {
                    List<ChannelReceivablesAccountTemp> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                            .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString())
                            .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_ONE)
                            .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_NEW_CAR));
                    if (accountList == null || accountList.size() == 0) {
                        return IResponse.fail("当前渠道汇款对象为主体，请录入新车款收款账号信息！");
                    }

                    List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                            .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString())
                            .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_TWO));
                    if (accountTempList == null || accountTempList.size() == 0) {
                        return IResponse.fail("当前渠道汇款对象为主体，请录入新车佣金收款账号信息！");
                    }
                }
            }

            //二手车验证
            if (IS_HAVE_CAR_ROLE_YES.equals(isOldCarRole)) {
                if (!StrUtil.isBlank(infoTemp.getChannelStatusOldCar())) {
                    infoTemp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_ZERO);
                }
                if (PAYMENT_OBJECT_ZERO.equals(infoTemp.getPaymentObject())) {
                    List<ChannelReceivablesAccountTemp> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                            .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString())
                            .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_ONE)
                            .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                    if (accountList == null || accountList.size() == 0) {
                        return IResponse.fail("当前渠道汇款对象为主体，请录入二手车车款收款账号信息！");
                    }

                    List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                            .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString())
                            .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_TWO)
                            .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                    if (accountTempList == null || accountTempList.size() == 0) {
                        return IResponse.fail("当前渠道汇款对象为主体，请录入二手车佣金收款账号信息！");
                    }
                }
            }

            channelOnlineService.updateById(infoTemp);

            //Step 2：同步信息到案件服务
            ChannelOnlineInterFaceVo vo = new ChannelOnlineInterFaceVo();
            vo.setChannelBaseInfo(infoTemp);

            //查询风控信息
            List<ChannelRiskInfoTemp> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId().toString()));
            List<ChannelRiskInfoTemp> riskInfoTempList = new ArrayList<>();
            if (channelRiskInfoTempList != null && channelRiskInfoTempList.size() > 0) {
                channelRiskInfoTempList.forEach(risk -> {
                    risk.setId(null);
                    riskInfoTempList.add(risk);
                });
                //返回风控数据
                vo.setRisk(riskInfoTempList);
            }
            //查询渠道保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoTempList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda().eq(ChannelQuotaInfoTemp::getChannelId, infoTemp.getId().toString()));
            List<ChannelQuotaInfoTemp> quotaInfoTempList = new ArrayList<>();
            if (channelQuotaInfoTempList != null && channelQuotaInfoTempList.size() > 0) {
                channelQuotaInfoTempList.forEach(quota -> {
                    quota.setId(null);
                    quotaInfoTempList.add(quota);
                });
                //返回渠道保证金信息
                vo.setQuota(quotaInfoTempList);
            }

            //查询渠道授权区域信息
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda().eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString()));
            List<ChannelAuthorizeRegionTemp> authorizeRegionTempList = new ArrayList<>();
            if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
                channelAuthorizeRegionTempList.forEach(authorize -> {
                    authorize.setId(null);
                    authorizeRegionTempList.add(authorize);
                });
                //返回授权区域信息
                vo.setRegion(authorizeRegionTempList);
            }

            List<ChannelReceivablesAccountTemp> accountList = new ArrayList<>();
            List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda().eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString()));
            if (accountTempList != null && accountTempList.size() > 0) {
                //修改收款账号状态为启用
                for (ChannelReceivablesAccountTemp accountTemp : accountTempList) {
                    accountTemp.setStatus(ACCOUNT_STATUS_ZERO);
                    channelAccountInfoService.updateById(accountTemp);
                    accountTemp.setId(null);
                    accountList.add(accountTemp);
                }
                //返回收款账号信息
                vo.setAcount(accountList);
            }

            //查询授权车型
            List<ChannelAuthorizeVehicleTemp> vehicleTempList = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda().eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString()));
            List<ChannelAuthorizeVehicleTemp> authorizeVehicleList = new ArrayList<>();
            if (vehicleTempList != null && vehicleTempList.size() > 0) {
                vehicleTempList.forEach(authorize -> {
                    authorize.setId(null);
                    authorizeVehicleList.add(authorize);
                });
                //返回授权车型
                vo.setVehicle(vehicleTempList);
            }
            channelOnlineService.synchronousDataToCase(vo);

            //Step 3：优先同步授权区域信息
            List<TsysAddressParam> paramList = service.list(Wrappers.<TsysAddressParam>query().lambda().orderByAsc(TsysAddressParam::getValue));
            ChannelRiskInfoTemp channelRiskNew = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
            ChannelRiskInfoTemp channelRiskOld = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
            List<ChannelAuthorizeRegionTemp> regionTempList = new ArrayList<>();
            if (channelRiskNew != null) {
                if (TYPE_NO.equals(channelRiskNew.getAuthRegionSwitch())) {
                    if (IS_HAVE_CAR_ROLE_YES.equals(isNewCarRole)) {
                        for (int i = 0; i < paramList.size(); i++) {
                            TsysAddressParam param = paramList.get(i);
                            ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                            tegionTemp.setCode(param.getValue());
                            tegionTemp.setIsParent(param.getIsParent() + "");
                            tegionTemp.setTitle(param.getLabel());
                            tegionTemp.setChannelId(infoTemp.getId());
                            tegionTemp.setParentId(param.getUpperCode());
                            tegionTemp.setBusinessType(BUSINESS_NEW_CAR);
                            regionTempList.add(tegionTemp);
                        }
                    }
                }
            }

            if (channelRiskOld != null) {
                if (TYPE_NO.equals(channelRiskOld.getAuthRegionSwitch())) {
                    if (IS_HAVE_CAR_ROLE_YES.equals(isOldCarRole)) {
                        for (int i = 0; i < paramList.size(); i++) {
                            TsysAddressParam param = paramList.get(i);
                            ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                            tegionTemp.setCode(param.getValue());
                            tegionTemp.setIsParent(param.getIsParent() + "");
                            tegionTemp.setTitle(param.getLabel());
                            tegionTemp.setChannelId(infoTemp.getId());
                            tegionTemp.setParentId(param.getUpperCode());
                            tegionTemp.setBusinessType(BUSINESS_OLD_CAR);
                            regionTempList.add(tegionTemp);
                        }
                    }
                }
            }

            ChannelAuthRegionCondition channelAuthRegionCondition = new ChannelAuthRegionCondition();
            if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
                channelAuthorizeRegionTempList.forEach(authorizeRegion -> {
                    if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                    } else if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                    }
                    regionTempList.add(authorizeRegion);
                });
            }
            channelAuthRegionCondition.setRegions(regionTempList);
            channelAuthRegionCondition.setType(AUTHORIZE_TYPE_ADD);
            channelOnlineService.synchronousAuthRegion(channelAuthRegionCondition);


            //Step 4:创建账号
            List<ChannelRiskInfoTemp> newRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
            List<ChannelRiskInfoTemp> oldRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
            ChannelBasicTempCondition dto = new ChannelBasicTempCondition();
            dto.setChannelId(infoTemp.getId());
            dto.setChannelAdmin(temp.getChannelAdmin());
            dto.setChannelCode(infoTemp.getChannelCode());
            dto.setChannelFullName(infoTemp.getChannelFullName());
            dto.setChannelType(infoTemp.getChannelType());
            dto.setHierarchy(infoTemp.getHierarchy());
            dto.setIdentityNumber(infoTemp.getChannelAdminIdCard());
            dto.setEmail(infoTemp.getChannelAdminMail());
            dto.setPhone(infoTemp.getChannelAdminTel());
            dto.setChannelBelong(infoTemp.getChannelBelong());
            dto.setChoiceCardealerSwitch(infoTemp.getChoiceCardealerSwitch());
            if (newRisk != null && newRisk.size() > 0) {
                dto.setNewCarUserHierarchy(newRisk.get(0).getAccountMaxNum());
            }
            if (oldRisk != null && oldRisk.size() > 0) {
                dto.setOldCarUserHierarchy(oldRisk.get(0).getAccountMaxNum());
            }
            channelOnlineService.createByParentId(dto);
        }

        //Step 5：“保证金缴纳记录”记录到档案中；将此次评级结果，记录到档案中；将“上线时间”记录到档案中
        List<ChannelArchivesInfo> channelArchivesInfoList = channelArchivesInfoService.list(Wrappers.<ChannelArchivesInfo>query().lambda()
                .eq(ChannelArchivesInfo::getChannelId, temp.getId().toString()));
        if (channelArchivesInfoList != null && channelArchivesInfoList.size() > 0) {
            for (ChannelArchivesInfo archivesInfo : channelArchivesInfoList) {
                channelArchivesInfoService.removeById(archivesInfo.getId());
            }
        }
        //判断当前登陆者是否拥有新车权限，由前端传入
        List<ChannelArchivesInfo> archivesInfoList = channelOnlineCondition.getChannelArchivesInfoList();
        if (IS_HAVE_CAR_ROLE_YES.equals(isNewCarRole)) {
            if (archivesInfoList != null && archivesInfoList.size() > 0) {
                channelArchivesInfoService.saveOrUpdateBatch(archivesInfoList);
            }
        }
        //判断当前登陆者是否拥有二手车权限，由前端传入
        List<ChannelArchivesInfo> archivesInfoOldList = channelOnlineCondition.getChannelArchivesInfoOldList();
        if (IS_HAVE_CAR_ROLE_YES.equals(isOldCarRole)) {
            if (archivesInfoOldList != null && archivesInfoOldList.size() > 0) {
                channelArchivesInfoService.saveOrUpdateBatch(archivesInfoOldList);
            }
        }

        return IResponse.success("提交成功");
    }

    @RequestMapping(value = "/channelSubmitWorkflow", method = RequestMethod.POST)
    @ApiOperation(value = "提交上线流程")
    @SysLog("提交上线流程")
    @Transactional(rollbackFor = Exception.class)
    public IResponse channelSubmitWorkflow(@RequestBody ChannelOnlineCondition channelOnlineCondition) {

        List list = new ArrayList<>();
        //渠道基本信息
        ChannelBaseInfoTemp temp = channelOnlineCondition.getChannelBaseInfoTemp();
        Long newId = temp.getId();
        if (!StrUtil.isBlank(temp.getSocUniCrtCode())) {
            List<ChannelBaseInfoTemp> socUniCrtCodeList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, temp.getSocUniCrtCode()));
            if (newId == null) {
                if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                    return IResponse.fail("当前统一社会信用代码已存在!");
                }
            } else {
                Long oldId = null;
                if (socUniCrtCodeList != null && socUniCrtCodeList.size() > 0) {
                    for (ChannelBaseInfoTemp baseInfoTemp : socUniCrtCodeList) {
                        oldId = baseInfoTemp.getId();
                        if (!oldId.equals(newId)) {
                            return IResponse.fail("系统已存在当前统一社会信用代码,操作失败!");
                        }
                    }
                }
            }
        }
        ChannelBaseInfoTemp baseInfoTemp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, newId));
        //管理员所在省市
        String[] channelAdminAddressValue = channelOnlineCondition.getChannelAdminAddressValue();
        //注册地所在省市
        String[] channelAddressValue = channelOnlineCondition.getChannelAddressValue();
        //办公所在省市
        String[] officeAddressValue = channelOnlineCondition.getOfficeAddressValue();
        //新车授权区域
        String[] mainArea = channelOnlineCondition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = channelOnlineCondition.getMainAreaOld();
        //主营品牌
        String[] mainBrand = channelOnlineCondition.getMainBrand();
        //授权车型
        String[] mainCar = channelOnlineCondition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = channelOnlineCondition.getMainCarOld();
        //判断管理员地址是否为空
        if (channelAdminAddressValue != null && channelAdminAddressValue.length > 0) {
            temp.setChannelAdminProvince(channelAdminAddressValue[0]);
            temp.setChannelAdminCity(channelAdminAddressValue[1]);
        }
        //判断注册省份是否为空
        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }
        //判断办公省份是否为空
        if (officeAddressValue != null && officeAddressValue.length > 0) {
            temp.setOfficeProvince(officeAddressValue[0]);
            temp.setOfficeCity(officeAddressValue[1]);
        }
        if (StrUtil.isBlank(temp.getChannelCode())) {
            //渠道代码为空则按照规则从新拼接
            temp.setChannelCode(channelOnlineService.channelCodeSequence(VALUE_CHANNEL_CODE, VALUE_CHANNEL_CODE));
        }
        //默认状态：草稿,只处理一次，没有对应权限更新为空
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {
            if (baseInfoTemp == null) {
                //新车渠道状态：审核中
                temp.setChannelStatus(VALUE_CHANNEL_STATUS_ONE);
            } else if (!VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatus())) {
                //新车渠道状态：审核中
                temp.setChannelStatus(VALUE_CHANNEL_STATUS_ONE);
            }
        } else {
            if (StrUtil.isBlank(temp.getChannelStatus())) {
                temp.setChannelStatus("");
            }
        }
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            if (baseInfoTemp == null) {
                //二手车渠道状态：审核中
                temp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_ONE);
            } else if (!VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatusOldCar())) {
                //二手车渠道状态：审核中
                temp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_ONE);
            }
        } else {
            if (StrUtil.isBlank(temp.getChannelStatusOldCar())) {
                temp.setChannelStatusOldCar("");
            }
        }
        //基本信息基本信息
        channelOnlineService.saveOrUpdate(temp);

        /** 保存渠道主营品牌信息前先清除旧的数据*/
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda().eq(ChannelMainBrand::getChannelId, temp.getId()));

        //保存渠道主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                channelMainBrand.setChannelBelong(temp.getChannelBelong());
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrandList.add(channelMainBrand);
            }
            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        //判断当前登陆者是否拥有新车权限，由前端传入
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {
            if (PAYMENT_OBJECT_ZERO.equals(temp.getPaymentObject())) {
                List<ChannelReceivablesAccountTemp> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString())
                        .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_ONE)
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_NEW_CAR));
                Assert.isTrue(accountList != null && accountList.size() != 0, "当前渠道汇款对象为主体，请录入新车款收款账号信息！");

                List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId())
                        .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_TWO)
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_NEW_CAR));
                Assert.isTrue(accountTempList != null && accountTempList.size() != 0, "当前渠道汇款对象为主体，请录入新车佣金收款账号信息！");
            }
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTemp();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);

            //保存新车保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }

            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveOrUpdateBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }

            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
        }

        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            if (PAYMENT_OBJECT_ZERO.equals(temp.getPaymentObject())) {
                List<ChannelReceivablesAccountTemp> accountList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId())
                        .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_ONE)
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                Assert.isTrue(accountList != null && accountList.size() != 0, "当前渠道汇款对象为主体，请录入二手车车款收款账号信息！");

                List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId())
                        .eq(ChannelReceivablesAccountTemp::getCollectionType, COLLECTION_TYPE_TWO)
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                Assert.isTrue(accountTempList != null && accountTempList.size() != 0, "当前渠道汇款对象为主体，请录入二手车佣金收款账号信息！");
            }

            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTempOld();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);

            //保存二手车保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempOldList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
            }
            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
        }

        //发起审批流程
        String isNewCarRole = channelOnlineCondition.getIsNewCarRole();
        String isOldCarRole = channelOnlineCondition.getIsOldCarRole();
        //判断拥有新车角色权限、且(渠道从未发起过新车审批流程)
        if (IS_HAVE_CAR_ROLE_YES.equals(isNewCarRole)) {
            //发起新车上线审批流程
            WorkTaskDetail workTaskDetail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda()
                    .eq(WorkTaskDetail::getBusinessKey, temp.getId())
                    .eq(WorkTaskDetail::getBusinessType, BUSINESS_TYPE_NEW_CAR));
            if (workTaskDetail == null) {
                StartFlowRequest startFlowNew = new StartFlowRequest();
                //枚举新车渠道上线
                startFlowNew.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_ONLINE_NEW));
                startFlowNew.setBizDataId(uidGenerator.getUID() + "");
                //枚举新车渠道上线
                startFlowNew.setFlowName((StringUtils.isEmpty(temp.getChannelFullName()) ? "" : (temp.getChannelFullName()) + "-") + AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_NEW));
                ObjectMapper mapper = new ObjectMapper();
                String json = null;
                try {
                    json = mapper.writeValueAsString(temp);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                JSONObject cancelJson = JSONObject.parseObject(json);
                //业务类型:新车
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE), BUSINESS_TYPE_NEW_CAR);
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BELONG), temp.getChannelBelong());
                workflowService.startWorkFlow(startFlowNew, cancelJson);

                //保存业务相关数据、用户前端逻辑判断
                WorkTaskDetail detail = new WorkTaskDetail();
                detail.setBizDataId(startFlowNew.getBizDataId());
                //新车
                detail.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                detail.setName(temp.getChannelFullName());
                detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_NEW));
                //渠道id绑定
                detail.setBusinessKey(temp.getId());
                workTaskDetailService.save(detail);
                ChannelOnlineWorkFlowCondition condition = new ChannelOnlineWorkFlowCondition();
                condition.setBusinessKey(temp.getId());
                condition.setBizDataId(startFlowNew.getBizDataId());
                condition.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_NEW));
                condition.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                workTaskApproveRecordService.startApproveSave(condition);

                List<ChannelReceivablesAccountTemp> accountNewList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId())
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_NEW_CAR));
                if (accountNewList != null && accountNewList.size() > 0) {
                    for (ChannelReceivablesAccountTemp accountTemp : accountNewList) {
                        accountTemp.setStatus(ACCOUNT_STATUS_ONE);
                        channelAccountInfoService.updateById(accountTemp);
                    }
                }
            }
        }
        //判断拥有二手车角色权限、且(渠道从未发起过二手车审批流程)
        if (IS_HAVE_CAR_ROLE_YES.equals(isOldCarRole)) {
            //发起二手车上线审批流程
            WorkTaskDetail workTaskDetail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda()
                    .eq(WorkTaskDetail::getBusinessKey, temp.getId())
                    .eq(WorkTaskDetail::getBusinessType, BUSINESS_TYPE_OLD_CAR));
            if (workTaskDetail == null) {
                StartFlowRequest startFlowOld = new StartFlowRequest();
                //枚举二手车渠道上线
                startFlowOld.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_ONLINE_OLD));
                startFlowOld.setBizDataId(uidGenerator.getUID() + "");
                //枚举二手车渠道上线
                startFlowOld.setFlowName((StringUtils.isEmpty(temp.getChannelFullName()) ? "" : (temp.getChannelFullName()) + "-") + AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_OLD));
                ObjectMapper mapper = new ObjectMapper();
                String json = null;
                try {
                    json = mapper.writeValueAsString(temp);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                JSONObject cancelJson = JSONObject.parseObject(json);
                //业务类型:二手车
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE), BUSINESS_TYPE_OLD_CAR);
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BELONG), temp.getChannelBelong());
                workflowService.startWorkFlow(startFlowOld, cancelJson);

                //保存业务相关数据、用户前端逻辑判断
                WorkTaskDetail detail = new WorkTaskDetail();
                detail.setBizDataId(startFlowOld.getBizDataId());
                //二手车
                detail.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                detail.setName(temp.getChannelFullName());
                detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_OLD));
                //渠道id绑定
                detail.setBusinessKey(temp.getId());
                workTaskDetailService.save(detail);
                ChannelOnlineWorkFlowCondition condition = new ChannelOnlineWorkFlowCondition();
                condition.setBusinessKey(temp.getId());
                condition.setBizDataId(startFlowOld.getBizDataId());
                condition.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_ONLINE_NEW));
                condition.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                workTaskApproveRecordService.startApproveSave(condition);

                List<ChannelReceivablesAccountTemp> accountOldList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                        .eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId())
                        .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                if (accountOldList != null && accountOldList.size() > 0) {
                    for (ChannelReceivablesAccountTemp accountTemp : accountOldList) {
                        accountTemp.setStatus(ACCOUNT_STATUS_ONE);
                        channelAccountInfoService.updateById(accountTemp);
                    }
                }
            }
        }

        return IResponse.success("提交成功");
    }

    @RequestMapping(value = "/modifyUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "启用渠道修改保存")
    @SysLog("启用渠道修改保存")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyUpdate(@RequestBody ChannelOnlineCondition channelOnlineCondition) {

        List list = new ArrayList<>();
        //渠道基本信息
        ChannelBaseInfoTemp temp = channelOnlineCondition.getChannelBaseInfoTemp();
        //管理员所在省市
        String[] channelAdminAddressValue = channelOnlineCondition.getChannelAdminAddressValue();
        //注册地所在省市
        String[] channelAddressValue = channelOnlineCondition.getChannelAddressValue();
        //办公所在省市
        String[] officeAddressValue = channelOnlineCondition.getOfficeAddressValue();
        //新车授权区域
        String[] mainArea = channelOnlineCondition.getMainArea();
        //二手车授权区域
        String[] mainAreaOld = channelOnlineCondition.getMainAreaOld();
        //主营品牌
        String[] mainBrand = channelOnlineCondition.getMainBrand();
        //授权车型
        String[] mainCar = channelOnlineCondition.getMainCar();
        //二手车授权车型
        String[] mainCarOld = channelOnlineCondition.getMainCarOld();
        //判断管理员地址是否为空
        if (channelAdminAddressValue != null && channelAdminAddressValue.length > 0) {
            temp.setChannelAdminProvince(channelAdminAddressValue[0]);
            temp.setChannelAdminCity(channelAdminAddressValue[1]);
        }
        //判断注册省份是否为空
        if (channelAddressValue != null && channelAddressValue.length > 0) {
            temp.setChannelProvince(channelAddressValue[0]);
            temp.setChannelCity(channelAddressValue[1]);
        }
        //判断办公省份是否为空
        if (officeAddressValue != null && officeAddressValue.length > 0) {
            temp.setOfficeProvince(officeAddressValue[0]);
            temp.setOfficeCity(officeAddressValue[1]);
        }
        channelOnlineService.saveOrUpdate(temp);
        list.add(temp);
        /** 保存渠道主营品牌信息前先清除旧的数据 */
        channelMainBrandService.remove(Wrappers.<ChannelMainBrand>query().lambda().eq(ChannelMainBrand::getChannelId, temp.getId()));

        //保存渠道主营品牌
        List<ChannelMainBrand> channelMainBrandList = new ArrayList<>();
        if (mainBrand != null && mainBrand.length > 0) {
            for (String main : mainBrand) {
                ChannelMainBrand channelMainBrand = new ChannelMainBrand();
                String code = main.split(",")[0];
                String title = main.split(",")[1];
                String indeterminate = main.split(",")[2];
                String carLevel = main.split(",")[3];
                String spellCode = main.split(",")[4];
                channelMainBrand.setChannelId(temp.getId());
                channelMainBrand.setCode(code);
                channelMainBrand.setTitle(title);
                channelMainBrand.setChannelBelong(temp.getChannelBelong());
                if (StrUtil.isNotBlank(indeterminate)) {
                    channelMainBrand.setIndeterminate(indeterminate);
                } else {
                    channelMainBrand.setIndeterminate("false");
                }
                if (StrUtil.isNotBlank(spellCode)) {
                    channelMainBrand.setSpellCode(spellCode);
                }
                channelMainBrand.setCarLevel(carLevel);
                channelMainBrandList.add(channelMainBrand);
            }
            int size = channelMainBrandList.size();
            if (size <= 1000) {
                channelMainBrandService.saveBatch(channelMainBrandList);
            } else {
                for (int i = 0; i < size / 1000; i++) {
                    if (size / 1000 - i > 1) {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, 1000 * i + 999));
                    } else {
                        channelMainBrandService.saveBatch(channelMainBrandList.subList(1000 * i, size - 1));
                    }
                }
            }
        }

        //判断当前登陆者是否拥有新车权限，由前端传入
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {
            ChannelOnlineInterFaceVo vo = new ChannelOnlineInterFaceVo();
            log.info("==================================基本信息组装开始==================================》");
            vo.setChannelBaseInfo(temp);
            log.info("==================================基本信息组装完毕==================================》");
            //保存渠道 新车风控信息前做清除
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            /** 保存渠道新车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTemp();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.saveOrUpdate(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);
            log.info("==================================新车风控信息组装开始==================================》");
            List<ChannelRiskInfoTemp> riskInfoTempList = new ArrayList<>();
            riskInfoTempList.add(channelRiskInfoTemp);
            vo.setRisk(riskInfoTempList);
            log.info("==================================新车风控信息组装完毕==================================》");

            //保存新车保证金信息
            List<ChannelQuotaInfoTemp> quotaInfoTempList = new ArrayList<>();
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                quotaInfoTempList.add(quotaInfo);
            }
            log.info("==================================新车保证金信息组装开始==================================》");
            vo.setQuota(quotaInfoTempList);
            log.info("==================================新车保证金信息组装结束==================================》");

            //保存渠道新车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainArea != null && mainArea.length > 0) {
                for (String area : mainArea) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            log.info("==================================新车授权区域信息组装开始==================================》");
            vo.setRegion(channelAuthorizeRegionTempList);
            log.info("==================================新车授权区域信息组装结束==================================》");

            //保存渠道新车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCar != null && mainCar.length > 0) {
                for (String main : mainCar) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_NEW_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            log.info("==================================新车授权车型信息组装开始==================================》");
            vo.setVehicle(channelAuthorizeVehicleList);
            log.info("==================================新车授权车型信息组装结束==================================》");

            //赋值业务类型
            vo.setBusinessType(BUSINESS_TYPE_NEW_CAR);
            log.info("==================================新车同步数据开始==================================》");
            AfsTransEntity<ChannelOnlineInterFaceVo> transEntity = new AfsTransEntity<>();
            transEntity.setTransCode(MqTransCode.CHANNEL_ONLINE_DEALER_INFO__TO_CASE);
            transEntity.setData(vo);
            channelOnlineInfoToCaseSender.sendForCaseChannelOnlineInfo(transEntity);
            //channelOnlineService.synchronousDataToCase(vo);
            log.info("==================================新车同步数据结束==================================》");
        }

        //判断当前登陆者是否拥有二手车权限，由前端传入
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            ChannelOnlineInterFaceVo vo = new ChannelOnlineInterFaceVo();
            log.info("==================================基本信息组装开始==================================》");
            vo.setChannelBaseInfo(temp);
            log.info("==================================基本信息组装完毕==================================》");

            //保存渠道二手车风控信息前做清除
            channelRiskInfoService.remove(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车保证金信息前先清除旧的数据*/
            channelQuotaInfoService.remove(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                    .eq(ChannelQuotaInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车授权区域信息前先清除旧的数据*/
            channelAuthorizeRegionService.remove(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                    .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车授权车型信息前先清除旧的数据*/
            channelAuthorizeVehicleTempService.remove(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                    .eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId())
                    .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));

            /** 保存渠道二手车风控信息*/
            ChannelRiskInfoTemp channelRiskInfoTemp = channelOnlineCondition.getChannelRiskInfoTempOld();
            //渠道id赋值
            channelRiskInfoTemp.setChannelId(temp.getId());
            channelRiskInfoService.save(channelRiskInfoTemp);
            list.add(channelRiskInfoTemp);
            log.info("==================================二手车风控信息组装开始==================================》");
            List<ChannelRiskInfoTemp> riskInfoTempList = new ArrayList<>();
            riskInfoTempList.add(channelRiskInfoTemp);
            vo.setRisk(riskInfoTempList);
            log.info("==================================二手车风控信息组装完毕==================================》");

            //保存二手车保证金信息
            List<ChannelQuotaInfoTemp> quotaInfoTempList = new ArrayList<>();
            List<ChannelQuotaInfoTemp> channelQuotaInfoList = channelOnlineCondition.getChannelQuotaInfoTempOldList();
            for (ChannelQuotaInfoTemp quotaInfo : channelQuotaInfoList) {
                quotaInfo.setChannelId(temp.getId());
                //临时额度
                BigDecimal tempQuota = quotaInfo.getTempQuota() == null ? BigDecimal.ZERO : quotaInfo.getTempQuota();
                //签放额度
                BigDecimal quotaSigning = quotaInfo.getQuotaAmount() == null ? BigDecimal.ZERO : quotaInfo.getQuotaAmount();
                //剩余额度 = 临时额度+签放额度
                quotaInfo.setSurplusQuota(tempQuota.add(quotaSigning));
                //占用额度为0
                quotaInfo.setOccupiedQuota(BigDecimal.ZERO);
                channelQuotaInfoService.saveOrUpdate(quotaInfo);
                quotaInfoTempList.add(quotaInfo);
            }
            log.info("=================================二手车保证金信息组装开始==================================》");
            vo.setQuota(quotaInfoTempList);
            log.info("==================================二手车保证金信息组装结束==================================》");

            //保存渠道二手车授权区域
            List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = new ArrayList<>();
            if (mainAreaOld != null && mainAreaOld.length > 0) {
                for (String area : mainAreaOld) {
                    ChannelAuthorizeRegionTemp regionTemp = new ChannelAuthorizeRegionTemp();
                    String code = area.split(",")[0];
                    String title = area.split(",")[1];
                    String isParent = area.split(",")[2];
                    String parentId = area.split(",")[3];
                    regionTemp.setChannelId(temp.getId());
                    regionTemp.setCode(code);
                    regionTemp.setTitle(title);
                    regionTemp.setIsParent(isParent);
                    regionTemp.setParentId(parentId);
                    regionTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeRegionTempList.add(regionTemp);
                }
                int size = channelAuthorizeRegionTempList.size();
                if (size <= 1000) {
                    channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeRegionService.saveBatch(channelAuthorizeRegionTempList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            log.info("==================================二手车授权区域信息组装开始==================================》");
            vo.setRegion(channelAuthorizeRegionTempList);
            log.info("==================================二手车授权区域信息组装结束==================================》");

            //保存渠道二手车授权车型
            List<ChannelAuthorizeVehicleTemp> channelAuthorizeVehicleList = new ArrayList<>();
            if (mainCarOld != null && mainCarOld.length > 0) {
                for (String main : mainCarOld) {
                    ChannelAuthorizeVehicleTemp channelAuthorizeVehicleTemp = new ChannelAuthorizeVehicleTemp();
                    String code = main.split(",")[0];
                    String title = main.split(",")[1];
                    String parentId = main.split(",")[2];
                    String indeterminate = main.split(",")[3];
                    String carLevel = main.split(",")[4];
                    String spellCode = main.split(",")[5];
                    String carType = main.split(",")[6];
                    channelAuthorizeVehicleTemp.setChannelId(temp.getId());
                    channelAuthorizeVehicleTemp.setCode(code);
                    channelAuthorizeVehicleTemp.setTitle(title);
                    channelAuthorizeVehicleTemp.setParentId(parentId);
                    channelAuthorizeVehicleTemp.setCarLevel(carLevel);
                    if("null".equals(carType)){
                        channelAuthorizeVehicleTemp.setCarType("");
                    }else{
                        channelAuthorizeVehicleTemp.setCarType(carType);
                    }
                    if (StrUtil.isNotBlank(indeterminate)) {
                        channelAuthorizeVehicleTemp.setIndeterminate(indeterminate);
                    } else {
                        channelAuthorizeVehicleTemp.setIndeterminate("false");
                    }
                    if (StrUtil.isNotBlank(spellCode)) {
                        channelAuthorizeVehicleTemp.setSpellCode(spellCode);
                    }
                    channelAuthorizeVehicleTemp.setBusinessType(BUSINESS_TYPE_OLD_CAR);
                    channelAuthorizeVehicleList.add(channelAuthorizeVehicleTemp);
                }
                int size = channelAuthorizeVehicleList.size();
                if (size <= 1000) {
                    channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList);
                } else {
                    for (int i = 0; i < size / 1000; i++) {
                        if (size / 1000 - i > 1) {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, 1000 * i + 999));
                        } else {
                            channelAuthorizeVehicleTempService.saveBatch(channelAuthorizeVehicleList.subList(1000 * i, size - 1));
                        }
                    }
                }
            }
            log.info("==================================二手车授权车型信息组装开始==================================》");
            vo.setVehicle(channelAuthorizeVehicleList);
            log.info("==================================二手车授权车型信息组装结束==================================》");

            //赋值业务类型
            vo.setBusinessType(BUSINESS_TYPE_OLD_CAR);
            log.info("==================================二手车同步数据开始==================================》");
            AfsTransEntity<ChannelOnlineInterFaceVo> transEntity = new AfsTransEntity<>();
            transEntity.setTransCode(MqTransCode.CHANNEL_ONLINE_DEALER_INFO__TO_CASE);
            transEntity.setData(vo);
            channelOnlineInfoToCaseSender.sendForCaseChannelOnlineInfo(transEntity);
            //channelOnlineService.synchronousDataToCase(vo);
            log.info("==================================二手车同步数据结束==================================》");
        }

        log.info("==================================进件授权同步数据开始==================================》");
        List<TsysAddressParam> paramList = service.list(Wrappers.<TsysAddressParam>query().lambda().orderByAsc(TsysAddressParam::getValue));
        List<ChannelAuthorizeRegionTemp> regionTempList = new ArrayList<>();
        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsNewCarRole())) {
            ChannelRiskInfoTemp channelRiskNew = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

            if (channelRiskNew != null) {
                if (TYPE_NO.equals(channelRiskNew.getAuthRegionSwitch())) {
                    for (int i = 0; i < paramList.size(); i++) {
                        TsysAddressParam param = paramList.get(i);
                        ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                        tegionTemp.setCode(param.getValue());
                        tegionTemp.setIsParent(param.getIsParent() + "");
                        tegionTemp.setTitle(param.getLabel());
                        tegionTemp.setChannelId(temp.getId());
                        tegionTemp.setParentId(param.getUpperCode());
                        tegionTemp.setBusinessType(BUSINESS_NEW_CAR);
                        regionTempList.add(tegionTemp);
                    }
                }
            }
        }

        if (IS_HAVE_CAR_ROLE_YES.equals(channelOnlineCondition.getIsOldCarRole())) {
            ChannelRiskInfoTemp channelRiskOld = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                    .eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                    .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
            if (channelRiskOld != null) {
                if (TYPE_NO.equals(channelRiskOld.getAuthRegionSwitch())) {
                    for (int i = 0; i < paramList.size(); i++) {
                        TsysAddressParam param = paramList.get(i);
                        ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                        tegionTemp.setCode(param.getValue());
                        tegionTemp.setIsParent(param.getIsParent() + "");
                        tegionTemp.setTitle(param.getLabel());
                        tegionTemp.setChannelId(temp.getId());
                        tegionTemp.setParentId(param.getUpperCode());
                        tegionTemp.setBusinessType(BUSINESS_OLD_CAR);
                        regionTempList.add(tegionTemp);
                    }
                }
            }
        }

        List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                .eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId()));
        ChannelAuthRegionCondition channelAuthRegionCondition = new ChannelAuthRegionCondition();
        ChannelBaseInfoTemp baseInfoTemp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, temp.getId()));
        if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
            if (VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatus()) && VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatusOldCar())) {
                log.info("=======判断新车渠道、二手车渠道是否已上线========》");
                channelAuthorizeRegionTempList.forEach(authorizeRegion -> {
                    if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                    } else if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                    }
                    regionTempList.add(authorizeRegion);
                });
            } else if (VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatus())) {
                log.info("=======判断新车渠道是否已上线========》");
                channelAuthorizeRegionTempList.forEach(authorizeRegion -> {
                    if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                        regionTempList.add(authorizeRegion);
                    }
                });
            } else if (VALUE_CHANNEL_STATUS_ZERO.equals(baseInfoTemp.getChannelStatusOldCar())) {
                log.info("=======判断二手车渠道是否已上线========》");
                channelAuthorizeRegionTempList.forEach(authorizeRegion -> {
                    if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                        authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                        regionTempList.add(authorizeRegion);
                    }
                });
            }
        }
        channelAuthRegionCondition.setRegions(regionTempList);
        channelAuthRegionCondition.setType(AUTHORIZE_TYPE_ADD);
        //同步授权区域到进件授权
        channelOnlineService.synchronousAuthRegion(channelAuthRegionCondition);

        List<ChannelRiskInfoTemp> newRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
        List<ChannelRiskInfoTemp> oldRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, temp.getId())
                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
        ChannelBasicTempCondition dto = new ChannelBasicTempCondition();
        dto.setChannelId(temp.getId());
        dto.setChannelAdmin(temp.getChannelAdmin());
        dto.setChannelCode(temp.getChannelCode());
        dto.setChannelFullName(temp.getChannelFullName());
        dto.setChannelType(temp.getChannelType());
        dto.setHierarchy(temp.getHierarchy());
        dto.setIdentityNumber(temp.getChannelAdminIdCard());
        dto.setEmail(temp.getChannelAdminMail());
        dto.setPhone(temp.getChannelAdminTel());
        dto.setChannelBelong(temp.getChannelBelong());
        dto.setChoiceCardealerSwitch(temp.getChoiceCardealerSwitch());
        dto.setChoiceCardealerSwitchOld(temp.getChoiceCardealerSwitchOld());
        if (newRisk != null && newRisk.size() > 0) {
            dto.setNewCarUserHierarchy(newRisk.get(0).getAccountMaxNum());
        }
        if (oldRisk != null && oldRisk.size() > 0) {
            dto.setOldCarUserHierarchy(oldRisk.get(0).getAccountMaxNum());
        }
        channelOnlineService.createByParentId(dto);
        log.info("==================================进件授权同步数据结束==================================》");
        return IResponse.success(list);
    }

    @RequestMapping(value = "/modifyRange", method = RequestMethod.POST)
    @ApiOperation(value = "批量修改经纬度范围")
    @SysLog("批量修改经纬度范围")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyRange(@RequestBody ChannelOnlineCondition channelOnlineCondition) {
        log.info("==================================批量修改渠道服务经纬度范围开始==================================》");
        List<ChannelBaseInfoTemp> tempList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda().in(ChannelBaseInfoTemp::getId, Arrays.asList(channelOnlineCondition.getChannelIds())));
        if (tempList != null && tempList.size() > 0) {
            tempList.forEach(temp -> {
                temp.setLongitudeLatitudeRange(channelOnlineCondition.getLlRangeModify());
            });
            channelOnlineService.saveOrUpdateBatch(tempList);
        }
        log.info("==================================批量修改渠道服务经纬度范围结束==================================》");
        log.info("==================================同步修改案件服务经纬度范围开始==================================》");
        channelOnlineService.synchronousLlRangeToCase(tempList);
        log.info("==================================同步修改案件服务经纬度范围结束==================================》");
        return IResponse.success("修改成功");
    }

    @RequestMapping(value = "/modifyManager", method = RequestMethod.POST)
    @ApiOperation(value = "批量修改渠道服务区域经理")
    @SysLog("批量修改渠道服务区域经理")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyManager(@RequestBody ChannelOnlineCondition channelOnlineCondition) {
        log.info("==================================批量修改渠道服务区域经理开始==================================》");
        List<ChannelRiskInfoTemp> riskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().in(ChannelRiskInfoTemp::getChannelId, Arrays.asList(channelOnlineCondition.getChannelIds())));
        if (riskInfoTempList != null && riskInfoTempList.size() > 0) {
            riskInfoTempList.forEach(temp -> {
                if (BUSINESS_TYPE_NEW_CAR.equals(temp.getBusinessType())) {
                    if (!StrUtil.isBlank(channelOnlineCondition.getCustomerManagerNew())) {
                        temp.setCustomerManager(channelOnlineCondition.getCustomerManagerNew());
                    }
                }
                if (BUSINESS_TYPE_OLD_CAR.equals(temp.getBusinessType())) {
                    if (!StrUtil.isBlank(channelOnlineCondition.getCustomerManagerOld())) {
                        temp.setCustomerManager(channelOnlineCondition.getCustomerManagerOld());
                    }
                }
            });
            channelRiskInfoService.saveOrUpdateBatch(riskInfoTempList);
        }
        log.info("==================================批量修改渠道服务区域经理结束==================================》");
        log.info("==================================同步修改案件区域经理开始==================================》");
        channelOnlineService.synchronousLlManagerToCase(channelOnlineCondition);
        log.info("==================================同步修改案件区域经理结束==================================》");
        return IResponse.success("修改成功");
    }

    // 地域树查询合作商信息
    @PostMapping(value = "/getByRegion")
    @ApiOperation(value = "多条件分页渠道信息列表")
    public IResponse<IPage<ChannelBaseInfoTemp>> getByRegion(@RequestBody RegionDTO condition) {
        //  这边获取我应该查询到的渠道id
        List<Long> channelIds = new ArrayList<>();
        BaseInfoTypeDTO dto = channelOnlineService.getRole();
        List<ChannelBaseInfoTemp> base = new ArrayList<>();


        // 判断传过来的类型
        if (condition.getNewCar() && condition.getOldCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR + "," + ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR);
            if (RoleTypeDic.ALL_CAR.equals(dto.getBusinessType()) && RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())) {
                // 这里说明我是全部属性
                base = channelOnlineService.getRoleChannelList();
            } else if (RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())) {
                // 说明我只有非直营的全部
                dto.setOwnBusinessType(null);
                base = channelOnlineService.getBaseInfoByStatusOnlyOtherAll(dto);
            } else if (RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())) {
                dto.setBusinessType(null);
                base = channelOnlineService.getBaseInfoByStatusOnlyOwnAll(dto);
            }
        } else if (condition.getNewCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR);
            if (!RoleTypeDic.OLD_CAR.equals(dto.getBusinessType()) && dto.getBusinessType() != null) {
                // 非直营包含新车属性
                dto.setBusinessType(RoleTypeDic.NEW_CAR);
                dto.setOwnBusinessType(null);
                List<ChannelBaseInfoTemp> newTemp = channelOnlineService.getBaseInfoByStatusOnlyOtherType(dto);
                if (newTemp.size() > 0) {
                    for (int i = 0; i < newTemp.size(); i++) {
                        channelIds.add(newTemp.get(i).getId());
                    }
                }
            }
            if (!RoleTypeDic.OLD_CAR.equals(dto.getOwnBusinessType()) && dto.getOwnBusinessType() != null) {
                // 直营属性包含新车属性
                dto.setBusinessType(null);
                dto.setOwnBusinessType(RoleTypeDic.NEW_CAR);
                List<ChannelBaseInfoTemp> newOwn = channelOnlineService.getBaseInfoByStatusOnlyOwnType(dto);
                if (newOwn.size() > 0) {
                    if (newOwn.size() > 0) {
                        for (int i = 0; i < newOwn.size(); i++) {
                            channelIds.add(newOwn.get(i).getId());
                        }
                    }
                }
            }
        } else if (condition.getOldCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR);
            if (!RoleTypeDic.NEW_CAR.equals(dto.getBusinessType()) && dto.getBusinessType() != null) {
                // 非直营包含二手车属性
                dto.setBusinessType(RoleTypeDic.OLD_CAR);
                dto.setOwnBusinessType(null);
                List<ChannelBaseInfoTemp> oldTemp = channelOnlineService.getBaseInfoByStatusOnlyOtherType(dto);
                if (oldTemp.size() > 0) {
                    for (int i = 0; i < oldTemp.size(); i++) {
                        channelIds.add(oldTemp.get(i).getId());
                    }
                }
            }
            if (!RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType()) && dto.getOwnBusinessType() != null) {
                // 直营属性包含二手车属性
                dto.setBusinessType(null);
                dto.setOwnBusinessType(RoleTypeDic.OLD_CAR);
                List<ChannelBaseInfoTemp> oldOwn = channelOnlineService.getBaseInfoByStatusOnlyOwnType(dto);
                if (oldOwn.size() > 0) {
                    if (oldOwn.size() > 0) {
                        for (int i = 0; i < oldOwn.size(); i++) {
                            channelIds.add(oldOwn.get(i).getId());
                        }
                    }
                }
            }
        } else {
            base = channelOnlineService.getRoleChannelList();
        }
        if (base.size() > 0) {
            for (int i = 0; i < base.size(); i++) {
                channelIds.add(base.get(i).getId());
            }
        }
        if (channelIds.size() <= 0) {
            return IResponse.fail("暂无匹配合作商信息！");
        }
        Set<String> code = new HashSet<>();
        // 判断传递过来的区域有多大
        List<String> codes = new ArrayList<>();
        if (condition.getRegionId() != null && condition.getRegionId() != "") {
            // 下面这个是没有用递归的  比较垃圾的算法
            if (RegionLevel.REGION_LEVEL_ONE.equals(condition.getRegionLevel().toString())) {
                List<ChannelAppertainRegion> list = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                        .lambda().eq(ChannelAppertainRegion::getLevel, "4"));
                if (list.size() > 0) {
                    for (ChannelAppertainRegion dep : list) {
                        codes.add(dep.getCode());
                    }
                }
            } else if (RegionLevel.REGION_LEVEL_TWO.equals(condition.getRegionLevel().toString())) {
                // 声明一个集合，获取所有的  自己下面 的3级 id
                List<Long> ids = new ArrayList<>();

                // 先查询出来所有的下级的id
                List<ChannelAppertainRegion> list = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                        .lambda().eq(ChannelAppertainRegion::getParentId, condition.getRegionId()));
                if (list.size() > 0) {
                    for (ChannelAppertainRegion dep : list) {
                        ids.add(dep.getId());
                    }
                    // 再去查询 4级别的数据
                    List<ChannelAppertainRegion> reg = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                            .lambda().in(ChannelAppertainRegion::getParentId, ids));
                    if (reg.size() > 0) {
                        for (ChannelAppertainRegion dep : reg) {
                            codes.add(dep.getCode());
                        }
                    }
                }
            } else if (RegionLevel.REGION_LEVEL_THREE.equals(condition.getRegionLevel().toString())) {
                // 先查询出来所有的下级的id
                List<ChannelAppertainRegion> list = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                        .lambda().eq(ChannelAppertainRegion::getParentId, condition.getRegionId()));
                if (list.size() > 0) {
                    for (ChannelAppertainRegion dep : list) {
                        codes.add(dep.getCode());
                    }
                }
            } else if (RegionLevel.REGION_LEVEL_FOUR.equals(condition.getRegionLevel().toString())) {
                // 说明这边就是市级别
                ChannelAppertainRegion c = appertainRegionService.getById(condition.getRegionId());
                codes.add(c.getCode());
            } else {
                throw new AfsBaseException(CommonConstants.FAIL, "获取区域树层级失败！");
            }
            // 下面是递归写法
//            if("4".equals(condition.getRegionLevel().toString())){
//                ChannelAppertainRegion c =appertainRegionService.getById(Long.valueOf(condition.getRegionId()));
//                codes.add(c.getCode());
//            }else {
//                ArrayList<String> regions = Lists.newArrayList();
//                this.getRegionIds(regions, Long.valueOf(condition.getRegionId()));
//                codes=regions;
//            }
        } else {
            List<ChannelAppertainRegion> list = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                    .lambda().eq(ChannelAppertainRegion::getLevel, "4"));
            if (list.size() > 0) {
                for (ChannelAppertainRegion dep : list) {
                    codes.add(dep.getCode());
                }
            }
        }
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        if (codes.size() == 0) {
            codes = null;
        }
        if (condition.getUserName() != null && condition.getUserName() != "") {
            List<ChannelRiskInfoTemp> risks = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query()
                    .lambda().eq(ChannelRiskInfoTemp::getCustomerManager, condition.getUserName()).in(ChannelRiskInfoTemp::getChannelId, channelIds));
            if (risks.size() > 0) {
                List<Long> cIds = new ArrayList<>();
                for (ChannelRiskInfoTemp c : risks) {
                    cIds.add(Long.valueOf(c.getChannelId()));
                }
                IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByRegion(page, condition, codes, cIds);
                return IResponse.success(channelList);
            } else {
                return IResponse.success(new ArrayList<>());
            }
        }
        IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByRegion(page, condition, codes, channelIds);
        return IResponse.success(channelList);
    }

    // 递归查询 地域树信息
    private void getRegionIds(ArrayList<String> region, Long deptId) {
        //查询二级分类的对象
        List<ChannelAppertainRegion> orgAuthorizeRegions = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                .lambda().eq(ChannelAppertainRegion::getParentId, deptId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (ChannelAppertainRegion orgAuthorizeRegion : orgAuthorizeRegions) {

            ChannelAppertainRegion deptAuthRegion = new ChannelAppertainRegion();
            BeanUtils.copyProperties(orgAuthorizeRegion, deptAuthRegion);
            if ("4".equals(deptAuthRegion.getLevel().toString())) {
                region.add(deptAuthRegion.getCode());
            }

            //把二级分类的每一个ID，查询它下面的子节点
            this.getRegionIds(region, deptAuthRegion.getId());
        }
    }

    // 批量修改区域经理人
    @Transactional
    @PostMapping("/batchManager")
    @ApiOperation(value = "批量修改区域经理")
    public IResponse<Boolean> batchManager(@RequestBody BatchManagerDTO dto) {
        String[] ids = dto.getIds().split(",");
        Set<Long> channelIds = new HashSet<>();
        if (ids.length > 0) {
            for (int j = 0; j < Arrays.asList(ids).size(); j++) {
                Long id = Long.valueOf(Arrays.asList(ids).get(j));
                channelIds.add(id);
            }
        }
        List<ChannelRiskInfoTemp> aa = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query()
                .lambda().eq(ChannelRiskInfoTemp::getBusinessType, dto.getBorder()).in(ChannelRiskInfoTemp::getChannelId, channelIds));
        if (aa.size() > 0) {
            aa.forEach(en -> {
                en.setCustomerManager(dto.getAreaManager());
            });
            channelRiskInfoService.updateBatchById(aa);
        }
        //  再去同步案件的数据
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("clientId", channelConfig.getCaseClientId());
        headers.put("clientSecret", channelConfig.getCaseClientSecret());
        IResponse result = channelUseCaseService.upCaseManager(dto, headers);
        if (!CommonConstants.SUCCESS.equalsIgnoreCase(result.getCode())) {
            throw new AfsBaseException("数据同步案件失败！！");
        }
        return new IResponse<Boolean>().setMsg("修改成功！");
    }

    // 渠道 发展查询合作商信息
    @PostMapping(value = "/getByDevelop")
    @ApiOperation(value = "多条件分页渠道信息列表用于渠道发展")
    public IResponse<IPage<ChannelBaseInfoTemp>> getByDevelop(@RequestBody DevelopDTO condition) {

        //  这边获取我应该查询到的渠道id
        List<Long> channelIds = new ArrayList<>();
        BaseInfoTypeDTO dto = channelOnlineService.getRole();
        List<ChannelBaseInfoTemp> base = new ArrayList<>();


        // 判断传过来的类型
        if (condition.getNewCar() && condition.getOldCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR + "," + ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR);
            if (RoleTypeDic.ALL_CAR.equals(dto.getBusinessType()) && RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())) {
                // 这里说明我是全部属性
                base = channelOnlineService.getRoleChannelList();
            } else if (RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())) {
                // 说明我只有非直营的全部
                dto.setOwnBusinessType(null);
                base = channelOnlineService.getBaseInfoByStatusOnlyOtherAll(dto);
            } else if (RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())) {
                dto.setBusinessType(null);
                base = channelOnlineService.getBaseInfoByStatusOnlyOwnAll(dto);
            }
        } else if (condition.getNewCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR);
            if (!RoleTypeDic.OLD_CAR.equals(dto.getBusinessType()) && dto.getBusinessType() != null) {
                // 非直营包含新车属性
                dto.setBusinessType(RoleTypeDic.NEW_CAR);
                dto.setOwnBusinessType(null);
                List<ChannelBaseInfoTemp> newTemp = channelOnlineService.getBaseInfoByStatusOnlyOtherType(dto);
                if (newTemp.size() > 0) {
                    for (int i = 0; i < newTemp.size(); i++) {
                        channelIds.add(newTemp.get(i).getId());
                    }
                }
            }
            if (!RoleTypeDic.OLD_CAR.equals(dto.getOwnBusinessType()) && dto.getOwnBusinessType() != null) {
                // 直营属性包含新车属性
                dto.setBusinessType(null);
                dto.setOwnBusinessType(RoleTypeDic.NEW_CAR);
                List<ChannelBaseInfoTemp> newOwn = channelOnlineService.getBaseInfoByStatusOnlyOwnType(dto);
                if (newOwn.size() > 0) {
                    if (newOwn.size() > 0) {
                        for (int i = 0; i < newOwn.size(); i++) {
                            channelIds.add(newOwn.get(i).getId());
                        }
                    }
                }
            }
        } else if (condition.getOldCar()) {
            condition.setBusinessType(ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR);
            if (!RoleTypeDic.NEW_CAR.equals(dto.getBusinessType()) && dto.getBusinessType() != null) {
                // 非直营包含二手车属性
                dto.setBusinessType(RoleTypeDic.OLD_CAR);
                dto.setOwnBusinessType(null);
                List<ChannelBaseInfoTemp> oldTemp = channelOnlineService.getBaseInfoByStatusOnlyOtherType(dto);
                if (oldTemp.size() > 0) {
                    for (int i = 0; i < oldTemp.size(); i++) {
                        channelIds.add(oldTemp.get(i).getId());
                    }
                }
            }
            if (!RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType()) && dto.getOwnBusinessType() != null) {
                // 直营属性包含二手车属性
                dto.setBusinessType(null);
                dto.setOwnBusinessType(RoleTypeDic.OLD_CAR);
                List<ChannelBaseInfoTemp> oldOwn = channelOnlineService.getBaseInfoByStatusOnlyOwnType(dto);
                if (oldOwn.size() > 0) {
                    if (oldOwn.size() > 0) {
                        for (int i = 0; i < oldOwn.size(); i++) {
                            channelIds.add(oldOwn.get(i).getId());
                        }
                    }
                }
            }
        } else {
            base = channelOnlineService.getRoleChannelList();
        }
        if (base.size() > 0) {
            for (int i = 0; i < base.size(); i++) {
                channelIds.add(base.get(i).getId());
            }
        }
        if (channelIds.size() <= 0) {
            return IResponse.fail("暂无匹配合作商信息！");
        }
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        List<Long> ids = new ArrayList<>();
        // 先判断下传递过来的哪层
        if (RegionLevel.REGION_LEVEL_ONE.equals(condition.getRegionLevel()) || condition.getRegionLevel() == null) {
            // 这边是点击全国或者初始化页面进这里
            if (channelIds.size() > 0) {
                if (condition.getUserName() != null && condition.getUserName() != "") {
                    List<ChannelRiskInfoTemp> risks = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query()
                            .lambda().eq(ChannelRiskInfoTemp::getCustomerManager, condition.getUserName()).in(ChannelRiskInfoTemp::getChannelId, channelIds));
                    if (risks.size() > 0) {
                        List<Long> cIds = new ArrayList<>();
                        for (ChannelRiskInfoTemp c : risks) {
                            cIds.add(Long.valueOf(c.getChannelId()));
                        }
                        IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, cIds);
                        return IResponse.success(channelList);
                    } else {
                        return IResponse.success(new ArrayList<>());
                    }
                }
                IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, channelIds);
                return IResponse.success(channelList);
            } else {
                return IResponse.success(new ArrayList<>());
            }
        } else {
            if (RegionLevel.REGION_LEVEL_TWO.equals(condition.getRegionLevel())) {
                //  声明一个集合放用户名
                List<String> userName = new ArrayList<>();
                // 进入这里说明是第二层  下级有d
                List<Long> userIds = new ArrayList<>();
                this.user(userIds, condition.getRegionId());
                userIds.add(condition.getUserId());
                List<ChannelUser> cUser = userService.list(Wrappers.<ChannelUser>query().lambda().in(ChannelUser::getUserId, userIds));
                if (cUser.size() > 0) {
                    for (ChannelUser c : cUser) {
                        userName.add(c.getUsername());
                    }
                    List<Long> useId = new ArrayList<>();
                    // 通过用户名去查询  区域经理叫这个的
                    List<ChannelRiskInfoTemp> risk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().in(ChannelRiskInfoTemp::getCustomerManager, userName));
                    if (risk.size() > 0) {
                        for (ChannelRiskInfoTemp t : risk) {
                            if (channelIds.contains(t.getChannelId())) {
                                useId.add(Long.valueOf(t.getChannelId()));
                            }
                        }
                        if (useId.size() > 0) {
                            if (condition.getUserName() != null && condition.getUserName() != "") {
                                List<ChannelRiskInfoTemp> risks = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query()
                                        .lambda().eq(ChannelRiskInfoTemp::getCustomerManager, condition.getUserName()).in(ChannelRiskInfoTemp::getChannelId, useId));
                                if (risks.size() > 0) {
                                    List<Long> cIds = new ArrayList<>();
                                    for (ChannelRiskInfoTemp c : risks) {
                                        cIds.add(Long.valueOf(c.getChannelId()));
                                    }
                                    IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, cIds);
                                    return IResponse.success(channelList);
                                } else {
                                    return IResponse.success(new ArrayList<>());
                                }
                            }
                            IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, useId);
                            return IResponse.success(channelList);
                        } else {
                            return IResponse.success(new ArrayList<>());
                        }


                    }
                }

            } else {
                // 直接查传递过来的用户id
                ChannelUser user = userService.getOne(Wrappers.<ChannelUser>query().lambda().eq(ChannelUser::getUserId, condition.getUserId()));
                if (user != null) {
                    List<ChannelRiskInfoTemp> risk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getCustomerManager, user.getUsername()));
                    List<Long> useId = new ArrayList<>();
                    if (risk.size() > 0) {
                        for (ChannelRiskInfoTemp t : risk) {
                            if (channelIds.contains(t.getChannelId())) {
                                useId.add(Long.valueOf(t.getChannelId()));
                            }
                        }
                        if (useId.size() > 0) {
                            if (condition.getUserName() != null && condition.getUserName() != "") {
                                List<ChannelRiskInfoTemp> risks = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query()
                                        .lambda().eq(ChannelRiskInfoTemp::getCustomerManager, condition.getUserName()).in(ChannelRiskInfoTemp::getChannelId, useId));
                                if (risks.size() > 0) {
                                    List<Long> cIds = new ArrayList<>();
                                    for (ChannelRiskInfoTemp c : risks) {
                                        cIds.add(Long.valueOf(c.getChannelId()));
                                    }
                                    IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, cIds);
                                    return IResponse.success(channelList);
                                } else {
                                    return IResponse.success(new ArrayList<>());
                                }
                            }
                            IPage<List<ChannelOnlineInfoVo>> channelList = channelOnlineService.getByDevelop(page, condition, useId);
                            return IResponse.success(channelList);
                        } else {
                            return IResponse.success(new ArrayList<>());
                        }
                    }
                }
            }
        }

        return IResponse.success(new ArrayList<>());
    }

    public void user(List<Long> allUserIds, String parentId) {
        // 说明展示的第三层，那么 level 就是 3和4的
        List<Long> threeRegion = new ArrayList<>();
        Set<Long> allIds = new HashSet<>();
        // 这个是查出来所有的归属第二级的第三级数据
        List<ChannelAppertainRegion> li = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                .lambda().eq(ChannelAppertainRegion::getParentId, parentId));
        if (li.size() > 0) {
            for (ChannelAppertainRegion l : li) {
                threeRegion.add(l.getId());
                allIds.add(l.getId());
            }
            List<ChannelAppertainRegion> fe = appertainRegionService.list(Wrappers.<ChannelAppertainRegion>query()
                    .lambda().in(ChannelAppertainRegion::getParentId, threeRegion));
            if (fe.size() > 0) {
                for (ChannelAppertainRegion f : fe) {
                    allIds.add(f.getId());
                }
            }
            // 查询出来用户的id
            if (allIds.size() > 0) {
                List<ChannelUserAppertain> appertain = userAppertainService.list(Wrappers.<ChannelUserAppertain>query().lambda().in(ChannelUserAppertain::getAppertainRegionId, allIds));
                if (appertain.size() > 0) {
                    for (ChannelUserAppertain u : appertain) {
                        allUserIds.add(u.getUserId());
                    }
                }
            }

        }
    }

    @RequestMapping(value = "/afterArchive", method = RequestMethod.POST)
    @ApiOperation(value = "贷后归档mq消息推送")
    @SysLog("贷后归档mq消息推送")
    @Transactional(rollbackFor = Exception.class)
    public IResponse afterArchive(@RequestBody ChannelOnlineCondition channelOnlineCondition) {
        log.info("==================================归档mq消息推送开始==================================》");
        List<ChannelBaseInfoTemp> tempList = channelOnlineService.list(Wrappers.<ChannelBaseInfoTemp>query().lambda()
                .in(ChannelBaseInfoTemp::getId, Arrays.asList(channelOnlineCondition.getChannelIds())));
        if (tempList != null && tempList.size() > 0) {
            for (ChannelBaseInfoTemp temp : tempList) {
                senderChannelToArchiveImpl.archivePushMQ(temp.getId().toString(), ArchiveConfig.wwsigndealer);
            }
        }
        log.info("==================================归档mq消息推送结束==================================》");
        return IResponse.success("推送成功");
    }

    @RequestMapping(value = "/getInfoBySocUniCrtCode/{socUniCrtCode}", method = RequestMethod.POST)
    @ApiOperation(value = "根据统一社会信用代码获取基本信息")
    public IResponse getInfoBySocUniCrtCode(@PathVariable String socUniCrtCode) {
        ChannelBaseInfoTemp temp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getSocUniCrtCode, socUniCrtCode));
        if (temp != null) {
            //新车或者二手车状态为启用状态情况下处理这种情况
            if (VALUE_CHANNEL_STATUS_ZERO.equals(temp.getChannelStatus()) || VALUE_CHANNEL_STATUS_ZERO.equals(temp.getChannelStatusOldCar())) {
                return IResponse.success(temp);
            }
        } else {
            return IResponse.success(false);
        }
        return IResponse.success(false);
    }
}
